﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using System.Collections.Specialized;
using Mvc.XForms.Utilities;

namespace Mvc.XForms.UI {
	public class LinqSortedList<T> : SortedList<T> {
		private readonly IQueryable<T> source;

		// Empty constructor so inherited objects can determine init order
		public LinqSortedList() { }

		public LinqSortedList(IQueryable<T> source, NameValueCollection collection, string sortExpressionKey, string sortDirectionKey, Expression<Func<T, object>> defaultSort, SortDirection defaultSortDirection)
			: this(source, collection, sortExpressionKey, sortDirectionKey, defaultSort.Body.ExtractID(), defaultSortDirection) { }

		public LinqSortedList(IQueryable<T> source, NameValueCollection collection, string sortExpressionKey, string sortDirectionKey, string defaultSortExpression, SortDirection defaultSortDirection)
			: this(source, new SortedParameters(collection, sortExpressionKey, sortDirectionKey, defaultSortExpression, defaultSortDirection)) { }

		public LinqSortedList(IQueryable<T> source, ISortedParameters gridParams) {
			this.source = source;
			InitWithParams(gridParams);
		}

		public LinqSortedList(IQueryable<T> source, string sortExpression, SortDirection sortDirection) {
			this.source = source;
			Init(sortExpression, sortDirection);
		}

		protected override void ApplySorting() {
			var sortedSource = source.Sort(SortExpression, SortDirection);
			Items = sortedSource.ToList();
		}
	}
}